package com.wlb.test.service.rabbitmq.publish;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.QueueingConsumer;
import com.wlb.test.util.rabbitmq.ConnectionUtil;
import com.wlb.test.util.rabbitmq.QueueEnum;

/**
 * @Author:wanglibing
 * @Mail:wanglibing@jd.com
 * @Date:Created in 14:44 2018/1/30
 * @Description:
 */
public class Recv2 {
    public static void main(String[] args) throws Exception{
        // 获取到连接以及mq通道
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();

        // 声明队列
        channel.queueDeclare(QueueEnum.QUEUE_NAME_FANOUT2.getName(), false, false, false, null);

        // 绑定队列到交换机
        channel.queueBind(QueueEnum.QUEUE_NAME_FANOUT2.getName(), QueueEnum.EXCHANGE_NAME.getName(), "");

        // 同一时刻服务器只会发一条消息给消费者
        channel.basicQos(1);

        // 定义队列的消费者
        QueueingConsumer consumer = new QueueingConsumer(channel);
        // 监听队列，手动返回完成
        channel.basicConsume(QueueEnum.QUEUE_NAME_FANOUT2.getName(), false, consumer);

        // 获取消息
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            System.out.println(" [x] Received2 '" + message + "'");
            Thread.sleep(10);
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }
    }
}
